package com.yan;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


/*
    消息生产者
 */
public class Producer {


    public static void main(String[] args) throws IOException, TimeoutException {
        //获取连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("1.116.195.238");
        factory.setPort(5672);
        //指定虚拟主机('/' 代指这个服务器)
        factory.setVirtualHost("/");
        factory.setUsername("root");
        factory.setPassword("root");

        //建立一个tcp连接 也可以使用线程池创建连接
        Connection connection = factory.newConnection();
//        Connection connection = factory.newConnection(Executors.newSingleThreadExecutor());
        //获取通道
        Channel channel = connection.createChannel();

        //声明一个队列    队列名称，是否持久化，是否排他，是否自动删除，消息队列属性信息
        channel.queueDeclare(QueueConstants.queueName, true, false, false, null);
        //声明一个交换器   交换器名称，类型，是否持久化，是否自动删除，交换器属性信息
        channel.exchangeDeclare(QueueConstants.exchangeName, BuiltinExchangeType.DIRECT, true, false, null);
        //将消息队列和交换器绑定 并指定路由键
        channel.queueBind(QueueConstants.queueName, QueueConstants.exchangeName, QueueConstants.routingKeyName);

        //向队列发送消息 交换器名字，路由键，消息内容属性，消息的字节数组
        channel.basicPublish(QueueConstants.exchangeName, QueueConstants.routingKeyName, null, "hello word yan2".getBytes());

        channel.close();
        connection.close();

    }

}
